#include "ssd1306.h"

#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <memory>

int play(char* video_bin)
{
    std::unique_ptr<FILE, decltype(&fclose)> fptr{fopen(video_bin, "rb"), fclose};

    uint32_t count = 0;
    uint8_t frame[SSD1306_BUFFER_SIZE] = {0};

    ssd1306_Init();
    uint32_t beg = HAL_GetTick();
    for(;;) {
        size_t nbytes = fread(frame, 1, sizeof(frame), fptr.get());
        if (ferror(fptr.get())) {
            printf("Error: %s\n", strerror(errno));
            return -1;
        }
        if (feof(fptr.get())) {
            break;
        }

        ssd1306_Fill(Black);
        ssd1306_DrawBitmap(frame, sizeof(frame));
        ssd1306_UpdateScreen();
        count++;
    }
    uint32_t end = HAL_GetTick();

    ssd1306_Fill(Black);
    ssd1306_UpdateScreen();
    ssd1306_Finish();

    float cost = (end - beg) / (float) HAL_GetTickFreq();
    printf("Total frames : %d\n", count);
    printf("Total time(s): %.3f\n", cost);
    printf("Average FPS  : %.3f\n", count / cost);
    return 0;
}

int main(int argc, char* argv[])
{
    if (argc <= 1) {
        printf("Usage: %s video.bin\n", argv[0]);
        return 1;
    }

    return play(argv[1]);
}